package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;

import java.io.IOException;

/**
 * @Author zlq
 * @CreateTime 2025/2/26
 */
@Component
@Slf4j
public class SearchReceiver {


    @Resource
    private SearchService searchService;

    @RabbitListener(bindings = {
        @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key={MqConst.ROUTING_ALBUM_UPPER}
         )
    })
    public void upperAlbum(Long albumId, Message message, Channel channel) {
        log.info("收到上架专辑消息，albumId:{}",albumId);

        try {
            if(null != albumId){
                //调用service
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("消费异常"+e.getMessage());
            throw new RuntimeException(e);
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RabbitListener(bindings ={
            @QueueBinding(
                    value = @Queue(value=MqConst.QUEUE_ALBUM_LOWER,durable = "true",autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
                    key = {MqConst.ROUTING_ALBUM_LOWER}
            )
    } )
    public void lowerAlbum(Long albumId, Message message, Channel channel) {
        log.info("收到下架专辑消息，albumId:{}",albumId);

        try {
            if(null != albumId){
                //调用service
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("消费异常"+e.getMessage());
            throw new RuntimeException(e);
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
